const Base = require('./base.js');

module.exports = class extends Base {
	constructor(ctx) {
		super(ctx);
		this.setup = this.model("system/setup");
	}
	async indexAction() {
		if(this.isGet) {
			return this.display();
		}

		let posts = this.post();
		
		
		let where = {};
		const data = await this.setup.dataTable(posts, where);
		return this.json(data);

	}

	async addAction() {
		if(this.isGet) {

			return this.display();
		}

		let posts = this.post();
		let setup = await this.setup.where({
			code: posts.code
		}).find();

		if(!think.isEmpty(setup)) {
			return this.fail("添加的项已存在");
		}

		let setup_id = await this.setup.add({
			code: posts.code,
			type: posts.type,
			name: posts.name,
			group: posts.group,
			extra: posts.extra,
			value: posts.value
		});
		if(setup_id == 0) {
			return this.fail("添加失败");
		}
		const setups = await this.setup.selectAll();
		think.config('setup', setups);
		return this.success("添加成功");

	}

	async editAction() {
		if(this.isGet) {
			let id = this.get("id");
			let setup = await this.setup.findOne(id);
			this.assign("setup", setup);
			return this.display();
		}

		let posts = this.post();
		let rows = await this.setup.setOne(posts.id,{
			code: posts.code,
			type: posts.type,
			name: posts.name,
			group: posts.group,
			extra: posts.extra,
			value: posts.value
		});
		if(rows == 0) {
			return this.fail("修改失败");
		}

		const setup = await this.setup.selectAll();
		think.config('setup', setup);

		return this.success("修改成功");
	}
	
	async deleteAction() {

		let id = this.post("id");
		let rows = await this.setup.where({
			id: id
		}).delete();
		if(rows == 0) {
			return this.fail("删除失败");
		}
		return this.success("删除成功");

	}
};